import Vue from 'vue'
import Vuex from 'vuex'
import api from '../api/index'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    shopList:[],//商品列表
    userId:window.localStorage.getItem('userId')||'' ,  //用户Id
    shopId:window.localStorage.getItem('shopId')||'',//商品ID
    detailInfo:{},//详情信息
    cartList:[]
  },
  mutations: {
    setState(state,payload){
      state[payload.key]=payload.val
    }
  },
  actions: {
    async getShoplist({commit},payload){     //获取商品列表
      api.getShop(payload).then(res=>{
        console.log(res)
        if(res.code===1){
         
          commit('setState',{key:'shopList',val:res.data.data})
        }
      })
    },
    async getLogin({commit},payload){     //登录
     let res=await api.getLogin(payload)
       console.log(res)
       const{code,data}=res
       if(code===1){
        const token=data.token
        window.localStorage.setItem('token',token)  //本地存储
        window.localStorage.setItem('userId',res.data.data.id); //获取用户id
        // commit('setState',{key:'userId',val:res.data.data.id})   
       }
       return res
    },
    async getDetail({commit},payload){   //获取详情
      // console.log(payload,'payload')
      let res=await api.getDetail(payload)
      const {code,data}=res;
      if(code===1){
        // window.localStorage.setItem('shopId',data.data[0].id); //获取用户id
        commit('setState',{key:'detailInfo',val:res.data.data[0]})
      }
    },
    async addCart({commit},payload){   //加入购物车
        let res=await api.ADDCart(payload)
        console.log(res)
        commit('setState',{key:'detailInfo',val:res.data.data[0]})
    },
    async getCartList({commit}){   //获取购物车数据
      console.log(this.state.userId,'this.state.userId')
      let res=await api.getCart({userId:this.state.userId})
      console.log(res)
      commit('setState',{key:'cartList',val:res.data})
    },
    async getCartCount({commit},payload){
      let res=await api.SETCount(payload)
      console.log(res)
    }
  },
  modules: {
  },
  getters:{

  }
})
